import { defineStore } from 'pinia';
import { Notify } from 'quasar';
import { useRoute } from 'vue-router';
import { copyToClipboard } from 'quasar';
// let paramsId = useRoute().params.id;
// if (typeof paramsId === 'string') {
//   paramsId = parseInt(useRoute().params.id);
// }

type MsgStores = {
  paramsId: number;
  conversationHistory: ConversationHistory[];
};
interface ConversationHistory {
  id: number;
  time?: number;
  msgData: MsgData[];
}
interface MsgData {
  sent: boolean;
  text: string;
  images?: string;
  src: string;
  name: string;
  id: number;
  loading?: boolean;
}
const defaultMsg = [
  {
    id: 1,
    msgData: []
  }
];
export const useMsgStores = defineStore('msgStores', {
  state: (): MsgStores => ({
    paramsId: parseInt(useRoute().params.id as string),
    conversationHistory:
      JSON.parse(localStorage.getItem('conversationHistory')) ??
      JSON.parse(JSON.stringify(defaultMsg))
  }),
  getters: {
    currentMesg(state) {
      if (!this.conversationHistory.length) {
        this.conversationHistory = JSON.parse(JSON.stringify(defaultMsg));
      }
      localStorage.setItem(
        'conversationHistory',
        JSON.stringify(state.conversationHistory)
      );
      const result = state.conversationHistory.find(
        item => item.id === state.paramsId
      );
      let id = null;
      if (result) {
        id = result.id;
      } else {
        id = state.conversationHistory[0].id;
      }
      if (!result && state.conversationHistory.length) {
        this.router.push({
          params: {
            id: id
          }
        });
      }
      return result;
    }
  },
  actions: {
    sendMeMsg(msgData: MsgData) {
      const defaultMsg = {
        sent: true,
        src: 'http://robt.cll.cool/images/dxn.jpg',
        name: '香香公主'
      };
      this.currentMesg.msgData?.push({ ...defaultMsg, ...msgData });
    },
    sendBatMsg(msgData: MsgData) {
      const msgDataState = this.currentMesg.msgData;
      const defaultMsg = {
        id: msgDataState.length,
        sent: false,
        text: '',
        src: 'http://robt.cll.cool/images/cll.jpg',
        name: '浪浪助手',
        loading: true
      };
      msgDataState.push({ ...defaultMsg, ...msgData });
      return msgDataState.length - 1;
    },
    updateMsg(id: number, text: string) {
      const msgDataState = this.currentMesg.msgData;
      const msgResult: MsgData | undefined = msgDataState.find(
        item => item.id === id
      );
      if (msgResult && text) {
        msgResult.text = msgResult.text + text;
        msgResult.loading = false;
      }
    },
    // 新增聊天
    newChat() {
      if (!this.conversationHistory.length) {
        this.conversationHistory = JSON.parse(JSON.stringify(defaultMsg));
      } else {
        this.conversationHistory.push({
          id:
            this.conversationHistory[this.conversationHistory.length - 1].id +
            1,
          msgData: [],
          time: new Date().getTime()
        });
      }
      this.router.push({
        params: {
          id: this.conversationHistory[this.conversationHistory.length - 1].id
        }
      });
    },
    setMsgId(paramsId: number) {
      this.paramsId = paramsId;
    },
    deleteMsg(id: number) {
      if (this.conversationHistory.length === 1) {
        Notify.create({
          position: 'top',
          type: 'negative',
          message: '请保持至少一条消息'
        });
        return;
      }
      const index = this.conversationHistory.findIndex(item => item.id === id);
      this.conversationHistory.splice(index, 1);
    },
    // 复制数据

    copyMsg(id: number) {
      const index = this.conversationHistory.findIndex(item => item.id === id);
      const msgData = JSON.stringify(this.conversationHistory[index].msgData);
      copyToClipboard(msgData)
        .then(() => {
          console.log('拷贝成功');
          Notify.create({
            position: 'top',
            type: 'positive',
            message: '拷贝成功'
          });
        })
        .catch(() => {
          Notify.create({
            position: 'top',
            type: 'negative',
            message: '拷贝失败'
          });
        });
    }
  }
});
